<?php

namespace App\Criteria\Personnel\Station;
use App\Libs\Tools\DataTables;
use App\Libs\Tools\SystemCodeConstant;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Prettus\Repository\Contracts\CriteriaInterface;
use Prettus\Repository\Contracts\RepositoryInterface;

class StationBaseQueryCriteria implements CriteriaInterface{

    public function apply($model, RepositoryInterface $repository){
        $name=Input::get('name');
        $station_class_id=Input::get('station_class_id');
        $model=$model->from('station as station')
                     ->leftjoin('station_class','station.station_class_id','=','station_class.id')
                     ->select(DB::raw('(select count(*) from user_station where station.id=user_station.station_id) as user_count, station.*,station_class.name as station_class_name'));
        if($name){$model=$model->where('station.name','like','%'.$name.'%');}
        if($station_class_id){$model=$model->where('station.station_class_id','=',$station_class_id);}
        $order_column_tag=DataTables::get_order_column_tag();
        if(!is_null($order_column_tag)){
            if($order_column_tag['order_column']=='station_class_name'){
                $model->orderBy('station_class.name',$order_column_tag['order_type']);
            }elseif($order_column_tag['order_column']=='user_count'){
                $model->orderBy('user_count',$order_column_tag['order_type']);
            }else{
                $model->orderBy('station.'.$order_column_tag['order_column'],$order_column_tag['order_type']);
            }
        }

        return $model;
    }
}